package com.learn.fiveday;

import com.google.common.collect.Lists;

import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.TimeUnit;

/**
 * @author ln
 * @Description: ${todo}
 * @date 2020/12/11
 */
public class SaleTicket {

    public static void main(String[] args) {
//        模拟多人买票
        TicketWindow ticketWindow = new TicketWindow(1000);

//        所有线程的集合
        ArrayList<Thread> threadList = Lists.newArrayList();
//        卖出的票数统计
        Vector<Integer> amountList = new Vector<>();

        for (int i = 0; i < 2000; i++) {
            Thread thread = new Thread(() -> {
//                买票
                int amount = ticketWindow.sell(randomAmount());
                amountList.add(amount);
            });
            threadList.add(thread);
            thread.start();
        }

        threadList.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });


        //    统计卖出的票数和剩余票数
        System.out.println("余票：" + ticketWindow.getCount());
        System.out.println("卖出去的票数：" + amountList.stream().mapToInt(i -> i).sum());
    }


    static Random random = new Random();

    //  1~5的随机数
    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }


}

//售票窗口
class TicketWindow {
    private int count;

    public TicketWindow(int count) {
        this.count = count;
    }

    //    获取余票数量
    public int getCount() {
        return count;
    }


    //    售票
    public synchronized int sell(int amount) {
        if (this.count >= amount) {
            this.count -= amount;
            return amount;
        } else {
            return 0;
        }
    }
}